package my.study.java.lang.annotation.Annotation.examples.example2;

import java.lang.reflect.Field;

public class Main {

	/**
	 * 利用注解生存简单的建表语句
	 * @param args
	 */
	public static void main(String[] args) {
		Class<?> cl = User.class;
		DBTable table = cl.getAnnotation(DBTable.class);
		StringBuilder sb = new StringBuilder();
		sb.append("create table " + table.name() + " (\n");
		for (Field field : cl.getDeclaredFields()) {
			String attribute = field.getName();
			Constraints cons = field.getAnnotation(Constraints.class);
			SqlType type = field.getAnnotation(SqlType.class);
			sb.append("    " + attribute + " " + type.type() + "(" + type.size() + ")");
			if (cons != null) {
				if (cons.primaryKey()) {
					sb.append(" PRIMARY KEY");
				} else if (cons.unique()) {
					sb.append(" UNIQUE");
				} else if (!cons.allowNull()) {
					sb.append(" NOT NULL");
				}
			}
			sb.append(",\n");
		}
		sb.append(");");
		pl(sb);
	}
	public static void pl(Object o) {
		System.out.println(o);
	}
}
